package com.hmall.search.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmall.search.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户身份获取拦截器
 */
@Component
@Slf4j
public class CommonInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是不是动态资源，如果不是就直接放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取当前的授权信息
        String authorization = request.getHeader("authorization");
        //如果为空，则抛出异常
        if (!"success".equals(authorization)){
            throw new LoginException("请使用网关访问");
        }
        //如果为不为空则授权信息并存入ThreadLocal中
        BaseContext.setAuthorization(authorization);
        //获取当前用户登录ID
        String userId = request.getHeader("userId");
        //如果为空，则抛出异常
        if (StringUtils.isBlank(userId)){
            throw new LoginException("请先登录后访问");
        }
        //如果为不为空则获取用户信息并存入ThreadLocal中
        BaseContext.setCurrentId(userId);
          return true;
    }
}
